import { Component, OnInit } from '@angular/core';
import {OAuthService} from "angular-oauth2-oidc";
//import {AuthService} from "../core/auth.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  userName?: string ="user1";
  password?: string;
  error?: string;
  _csrf?: string;
  loginFailed: boolean = false;
  userProfile?: object | undefined;

  constructor(private oauthService: OAuthService) {  }


  // canLogin(): boolean {
  //   return !!this.username && !!this.password;
  // }

  // onSubmit() {
  //   if (this.canLogin()) {
  //     // 这里需要使用POST请求将用户名和密码发送到Spring Security的认证端点
  //     // 由于angular-oauth2-oidc库不直接支持发送用户名和密码，你需要自定义这个逻辑
  //     // 通常，这涉及到向授权服务器的登录端点发送POST请求
  //     // 注意：这一步通常不是OAuth2的标准做法，因为OAuth2通常使用授权码流或隐式流，而不是直接发送用户名和密码
  //     // 但如果你的Spring Security配置支持这样的方式，你可以使用HttpClient来实现
  //     // 示例代码：
  //     this.authService.tryLogin();
  //   }
  // }

  ngOnInit(): void {
    // this._csrf = this.authService.initLoginFlow();
    // this.authService.getError().subscribe(error => {
    //   this.error = error;
    // });
    //
    // this.authService.login(username, password, _csrf);
  }

  loadUserProfile(): void {
    this.oauthService.loadUserProfile().then((up) => (this.userProfile = up));
  }

  get access_token() {
    return this.oauthService.getAccessToken();
  }

  get access_token_expiration() {
    return this.oauthService.getAccessTokenExpiration();
  }

  get user1Name():string | null {
    var claims = this.oauthService.getIdentityClaims();
    if (!claims) return null;
    // @ts-ignore
    return claims['sub'];  //given_name
  }

  get familyName() {
    var claims = this.oauthService.getIdentityClaims();
    if (!claims) return null;
    // @ts-ignore
    return claims['family_name'];
  }

  loginWithPassword() {
    if (this.userName != null && this.password != null) {
      this.oauthService
        //.fetchTokenUsingPasswordFlowAndLoadUserProfile(
        .fetchTokenUsingPasswordFlow(
          this.userName,
          this.password,
          //{grant_type:'authorization_code'}
        )
        .then(() => {
          console.debug('successfully logged in');
          this.loginFailed = false;
        })
        .catch((err) => {
          console.error('error logging in', err);
          this.loginFailed = true;
        });
    }
  }

  logout() {
    this.oauthService.logOut(true);
  }

}
